import subprocess
import os
from pathlib import Path
from ..file_processor import FileProcessor
import tempfile

class DocToMarkdownProcessor(FileProcessor):
    def __init__(self, input_filepath: str, output_filepath: str, options: dict = {}, lua_script: str = None):
        super().__init__(input_filepath, output_filepath, options)
        if lua_script is None:
            # 自动获取默认 Lua 脚本的路径
            self.lua_script = str(Path(__file__).parent / 'improve_headers.lua')
        else:
            self.lua_script = lua_script

    def _process_file(self):
        # 确定输入文件的格式
        _, file_extension = os.path.splitext(self.input_filepath)
        input_format = file_extension.lower()[1:]  # 移除点号

        if input_format == 'doc':
            # 如果是 .doc 文件，先转换为 .docx
            with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as temp_file:
                temp_docx = temp_file.name

            try:
                subprocess.run(['unoconv', '-f', 'docx', '-o', temp_docx, self.input_filepath], check=True)
                input_file = temp_docx
                input_format = 'docx'
            except subprocess.CalledProcessError:
                print("Error: unoconv failed to convert .doc to .docx. Make sure unoconv is installed.")
                return {'success': False, 'error': 'Failed to convert .doc to .docx'}
        else:
            input_file = self.input_filepath

        pandoc_options = self.options.get('pandoc_options', [
            '-f', input_format,
            '-t', 'markdown_strict+pipe_tables+table_captions+yaml_metadata_block'
        ])

        # 添加 Lua 脚本到 pandoc 选项中
        if os.path.exists(self.lua_script):
            pandoc_options.extend(['--lua-filter', self.lua_script])
        else:
            print(f"Warning: Lua script not found at {self.lua_script}")

        # 将处理后的文档转换为 Markdown
        try:
            subprocess.run(['pandoc'] + pandoc_options + [input_file, '-o', self.output_filepath], check=True)
        except subprocess.CalledProcessError as e:
            return {'success': False, 'error': str(e)}
        finally:
            if input_format == 'doc':
                os.unlink(temp_docx)

        return {'success': True}

    @classmethod
    def main(cls):
        import argparse
        parser = argparse.ArgumentParser(description="Convert Doc/Docx to Markdown with optional Lua filtering.")
        parser.add_argument("-i", "--input", required=True, help="Path to the input file")
        parser.add_argument("-o", "--output", required=True, help="Path to the output file")
        parser.add_argument("-l", "--lua-script", help="Path to the Lua script for filtering (optional)")
        args = parser.parse_args()

        processor = cls(args.input, args.output, lua_script=args.lua_script)
        result = processor.process()
        print(result)

def test(arg={}):
    # Usage example
    processor = DocToMarkdownProcessor("input.doc", "output/converted.md")
    result = processor.process()
    print(result)




if __name__ == "__main__":
    DocToMarkdownProcessor.main()

# 使用示例：
# python3 doc_to_markdown.py -i input.docx -o output/doc_converted.md
# python3 doc_to_markdown.py -i input.doc -o output/doc_converted.md

"""
可以通过以下方式运行：
python3 -m document2llm.md.doc2md.doc_to_markdown -i input.docx -o output/doc_converted.md


document2llm_doc2md -i input.docx -o output/doc_converted2.md
"""



"""

from document2llm.md.doc2md.doc_to_markdown   import DocToMarkdownProcessor

processor = DocToMarkdownProcessor("input.docx", "output/converted-doc2.md")
result = processor.process()
print(result)
"""


#
